/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#include "Xern/Console.hpp"
#include "Xern/Log.hpp"

#define MAX_BUFFER_SIZE 2048

namespace Xern
{

	// Console implementation
	Console::Console()
	{
	}

	Console::~Console()
	{
	}

	void Console::Print(const char *fmt, ...)
	{
		char tmp[MAX_BUFFER_SIZE];
		va_list list;

		va_start(list, fmt);
		vsnprintf(tmp, MAX_BUFFER_SIZE, fmt, list);
		LogConsole->Print("%s", tmp);
		va_end(list);
	}

	static bool IsAlpha(char c)
	{
		if((c >= 'a' && c <= 'z') ||
				(c >= 'A' && c <= 'Z'))
			return true;
		return false;
	}

	static bool IsNumber(char c)
	{
		if(c >= '0' && c <= '9')
			return true;
		return false;
	}

	static bool IsHexNumber(char c)
	{
		if(IsNumber(c))
			return true;
		else if((c >= 'a' && c <= 'f') ||
				(c >= 'A' && c <= 'F'))
			return true;
		return false;
	}

	static bool IsIdentStart(char c)
	{
		if(IsAlpha(c))
			return true;
		bool ret;
		switch(c)
		{
		case '+':
		case '-':
		case '/':
		case '*':
		case '!':
			ret = true;
			break;
		default:
			ret = false;
			break;
		}
		return ret;
	}

	static bool IsIdent(char c)
	{
		if(IsIdentStart(c))
			return true;
		else if(IsNumber(c))
			return true;
		else if(c == '_')
			return true;
		else if(c == '.')
			return true;
		return false;
	}

	int Console::ExecCommand(const char *cmd)
	{
		std::vector<std::string> arguments;
		const char *p = cmd;
		char tmp[2048];
		int ret = 0;
		char *d;

	skipwhite:
		d = tmp;
		memset(tmp, 0, sizeof(tmp));

		while(*p <= ' ')
		{
			// Skip escape sequences
			if(*p == 0)
			{
				goto exec_cmd;
			}
			else if(*p == 033)
			{
				while(*p != 'm')
					p++;
				p++;
			}
			else if(*p == '\n' || (*p == '\r' && p[1] != '\n'))
			{
				p++;
				goto exec_cmd;
			}
			else if(*p == '\\')
			{
				p++;
				switch(*p)
				{
				case 't':
				case 'n':
				case 'r':
				case ' ':
					p++;
					break;
				default:
					goto skipwhite;
				}
			}
			p++;
		}

		// Parse identifiers
		if(IsIdentStart(*p))
		{
			*d++ = *p++;
			while(IsIdent(*p))
			{
				*d++ = *p++;
			}
			arguments.push_back(tmp);
			goto skipwhite;
		}

		// Parse hex numbers
		if(*p == '0' && (p[1] == 'x' || p[1] == 'X'))
		{
			*d++ = *p++;
			*d++ = *p++;
			while(IsHexNumber(*p))
			{
				*d++ = *p++;
			}
			arguments.push_back(tmp);
			goto skipwhite;
		}

		// Parse numbers
		if(IsNumber(*p) || *p == '.')
		{
			while(IsNumber(*p) || *p == '.')
			{
				*d++ = *p++;
			}
			arguments.push_back(tmp);
			goto skipwhite;
		}

		// Parse extra commands
		if(*p == ';')
		{
			p++;
			goto exec_cmd;
		}

		// Parse simple literals
		if(*p == '\'')
		{
			p++;
			while(*p != '\'' && *p != 0)
			{
				*d++ = *p++;
			}
			if(*p == '\'')
				p++;
		}
		// Parse double literals
		else if(*p == '"')
		{
			p++;
			while(*p != '"' && *p != 0)
			{
				if(*p == '\\')
				{
					p++;
					switch(*p)
					{
					case 'n':
						*d++ = '\n';
						break;
					case 'r':
						*d++ = '\r';
						break;
					case 't':
						*d++ = '\t';
						break;
					case 0:
						break;
					default:
						*d++ = *p;
						break;
					}
					p++;
				}
				else
				{
					*d++ = *p++;
				}
			}
			p++;
		}
		else
			*d++ = *p++;
		arguments.push_back(tmp);
		goto skipwhite;

	exec_cmd:

		// Convert the arguments
		int argc = arguments.size();
		const char **argv = (const char **)malloc(sizeof(const char *) * (argc + 1));
		for(int i = 0; i < argc; i++)
		{
			argv[i] = arguments[i].c_str();
		}

		// Execute the command
		ret = ExecCommand(argc, argv);

		// Free the arguments
		free(argv);

		// Make next command call
		if(*p != 0)
		{
			arguments.clear();
			goto skipwhite;
		}

		return ret;
	}

	int Console::ExecCommand(int argc, const char *argv[])
	{
		// If not command is specified, silently return
		if(argc <= 0)
			return 0;
		boost::unique_lock<boost::mutex> l(consoleMutex);
		// Check the console variables
		variables_type::iterator vf = variables.find(argv[0]);
		if(vf != variables.end())
		{
			boost::shared_ptr<IConsoleVariable> var = vf->second;
			if(argc >= 2)
			{
				var->SetValue(argv[1]);
			}
			else
			{
				Print("'%s'='%s'", var->GetName(), var->GetValue());
			}

			return true;
		}

		// Check the console commands
		commands_type::iterator f = commands.find(argv[0]);
		if(f != commands.end())
			return f->second->Main(argc, argv);

		subconsoles_type::iterator it = subconsoles.begin();
		for(; it != subconsoles.end(); it++)
		{
			boost::shared_ptr<IConsole> con = *it;
			if(con->ContainsVariable(argv[0]) || con->ContainsCommand(argv[0]))
				return con->ExecCommand(argc, argv);
		}

		LogConsole->Error("Invalid command: '%s'", argv[0]);
		return -10;
	}

	bool Console::ContainsVariable(const char *varname)
	{
		boost::unique_lock<boost::mutex> l(consoleMutex);
		variables_type::iterator f = variables.find(varname);
		if(f != variables.end())
			return true;
		subconsoles_type::iterator it = subconsoles.begin();
		for(; it != subconsoles.end(); it++)
		{
			boost::shared_ptr<IConsole> subcon = *it;
			if(subcon->ContainsVariable(varname))
				return true;
		}
		return false;
	}

	bool Console::ContainsCommand(const char *cmd)
	{
		boost::unique_lock<boost::mutex> l(consoleMutex);
		commands_type::iterator f = commands.find(cmd);
		if(f != commands.end())
			return true;
		subconsoles_type::iterator it = subconsoles.begin();
		for(; it != subconsoles.end(); it++)
		{
			boost::shared_ptr<IConsole> subcon = *it;
			if(subcon->ContainsCommand(cmd))
				return true;
		}
		return false;
	}

	bool Console::SetConsoleVariable(const char *var, const char *value)
	{
		boost::unique_lock<boost::mutex> l(consoleMutex);
		variables_type::iterator f = variables.find(var);
		if(f != variables.end())
		{
			boost::shared_ptr<IConsoleVariable> tvar = f->second;
			tvar->SetValue(value);
			return true;
		}
		return false;
	}

	bool Console::RegisterVariable(boost::shared_ptr<IConsoleVariable> var)
	{
		boost::unique_lock<boost::mutex> l(consoleMutex);
		return variables.insert(variables_type::value_type(var->GetName(), var))
			   .second;
	}

	bool Console::RegisterCommand(boost::shared_ptr<IConsoleCommand> cmd)
	{
		boost::unique_lock<boost::mutex> l(consoleMutex);
		return commands.insert(commands_type::value_type(cmd->GetName(), cmd))
			   .second;
	}

	bool Console::RegisterSubConsole(boost::shared_ptr<IConsole> subcon)
	{
		boost::unique_lock<boost::mutex> l(consoleMutex);
		return subconsoles.insert(subcon).second;
	}

	// ConsoleVariable implementation
	ConsoleVariable::ConsoleVariable(const char *name,
									 const char *defaultValue,
									 const char *description)
	{
		name_ = name;
		value_ = defaultValue;
		description_ = description;
	}

	ConsoleVariable::~ConsoleVariable()
	{
	}

	const char *ConsoleVariable::GetName() const
	{
		return name_;
	}

	const char *ConsoleVariable::GetDescription() const
	{
		return description_;
	}

	const char *ConsoleVariable::GetValue() const
	{
		return value_.c_str();
	}

	void ConsoleVariable::SetValue(const char *value)
	{
		this->value_ = value;
	}

} // namespace Xern
